package com.bergliege.subject.application.controller;

import com.alibaba.fastjson.JSON;
import com.bergliege.subject.application.convert.SubjectCategoryDTOConverter;
import com.bergliege.subject.application.dto.SubjectCategoryDTO;
import com.bergliege.subject.common.entity.Result;
import com.bergliege.subject.domain.entity.SubjectCategoryBO;
import com.bergliege.subject.domain.service.SubjectCategoryDomainService;
import com.bergliege.subject.infra.basic.entity.SubjectCategory;
import com.bergliege.subject.infra.basic.service.SubjectCategoryService;
import com.bergliege.subject.infra.basic.service.impl.SubjectCategoryServiceImpl;
import com.google.common.base.Preconditions;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/subject/category")
@Slf4j
public class SubjectCategoryController {

    @Resource
    private SubjectCategoryDomainService subjectCategoryDomainService;

    @Autowired
    private SubjectCategoryServiceImpl subjectCategoryService;

    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody SubjectCategoryDTO subjectCategoryDTO){
        try{
            if(log.isInfoEnabled()){
                log.info("SubjectCategoryController.add.dto: {}", JSON.toJSONString(subjectCategoryDTO));
            }

            Preconditions.checkNotNull(subjectCategoryDTO.getCategoryType(),"分类类型不能为空");
            Preconditions.checkArgument(!StringUtils.isNullOrEmpty(subjectCategoryDTO.getCategoryName()),"分类名称不能为空");
            Preconditions.checkNotNull(subjectCategoryDTO.getParentId(),"分类父级id不能为空");

            SubjectCategoryBO subjectCategoryBO = SubjectCategoryDTOConverter.INSTANCE.converDtoToCategoryBo(subjectCategoryDTO);
            subjectCategoryDomainService.add(subjectCategoryBO);
            SubjectCategory subjectCategory = subjectCategoryService.queryById(1L);
            return Result.ok(true);
        }catch (Exception e){
            log.error("SubjectCategoryController.add.error()", e.getMessage(),e);
            return Result.fail(e.getMessage());
        }
    }
}
